/**
 * Created by hillchen on 2017/11/16.
 */
function isNumVal(_val) {
    return (/^-?\d+$/).test(_val + '');
}
Vue.component('input-number',{
    template:'<div><input type="text" :value="currentValue" @change="handleChange"/>' +
    '<button :disabled="min >= currentValue " @click="handleDown">-</button>' +
    '<button :disabled="max <= currentValue " @click="handleUp">+</button>' +
    '</div>',
    props: {
        min: {
            type: Number,
            default: -Infinity
        },
        max: {
            type: Number,
            default: Infinity
        },
        value: {
            type: Number,
            default: 0
        }
    },
    data: function () {
        return {
            currentValue: this.value
        }
    },
    watch: {
        currentValue: function (val) {
            this.$emit('input',val);
            this.$emit('on-change',val);
        },
        value: function (val) {
            this.updateValue(val) ;
        }
    },
    methods: {
        handleDown: function () {
            if(this.min < this.currentValue){
                this.currentValue --;
            }
        },
        handleUp: function () {
            if(this.max > this.currentValue){
                this.currentValue ++;
            }
        },
        updateValue: function (_val) {
            this.currentValue = _val > this.max ? this.max : _val < this.min ? this.min : _val;
        },
        handleChange: function (event) {
            let _val = event.target.value.trim();

            if(isNumVal(_val)){
                _val = Number(_val);
                this.updateValue(_val);
            }else{
                event.target.value = this.currentValue;
            }
        },
        mounted: function () {
            this.updateValue(this.value);
        }
    }
});
